<template>
  <div id="app">
    <Header
      v-if="questions.length"
      :counter="index + 1 + '/' + questions.length"
    />
    <b-container class="bv-example-row">
      <b-row>
        <b-col sm="6" offset="3">
          <QuestionBox
            v-if="questions.length"
            :question="questions[index].question"
            :answerList="questions[index].answerList"
            :onSubmit="submit"
            :onNext="nextQustion"
            :onSelect="selector"
          />
        </b-col>
      </b-row>
    </b-container>
  </div>
</template>

<script>
import { Header, QuestionBox } from "./components";

export default {
  name: "App",
  components: { Header, QuestionBox },
  data() {
    return {
      questions: [],
      index: 0,
      answer: "",
    };
  },
  mounted() {
    // if (this.questions.length < 1) {
    fetch("https://opentdb.com/api.php?amount=10&category=27&type=multiple", {
      method: "get",
    })
      .then((e) => {
        return e.json();
      })
      .then((jsonData) => {
        if (jsonData.response_code === 0) {
          jsonData.results.forEach((question) => {
            question.answerList = this.getRandomList([
              ...question.incorrect_answers,
              question.correct_answer,
            ]);
            this.questions.push(question);
          });
        }
      });
    // }
  },
  computed: {
    correctAnswer() {
      return this.questions[this.index].correct_answer;
    },
  },
  methods: {
    getRandomList(listArr) {
      let list = [...listArr];
      for (let index = 0; index < list.length; index++) {
        let rIndex = Math.floor(Math.random() * list.length);
        [list[index], list[rIndex]] = [list[rIndex], list[index]];
      }
      console.log("list------>", list);
      return list;
    },
    nextQustion() {
      this.index++;
      this.currentAnswer = "";
      if (this.index > this.questions.length - 1) {
        this.index = 0;
      }
      let items = document.getElementsByClassName("list-group-item");
      items.forEach((item) => {
        item.style.backgroundColor = "";
      });
    },
    selector(answer) {
      this.answer = answer;
    },
    submit() {
      console.log(this.answer, "<---------this.answer");
      let correctItem = document.getElementById(this.correctAnswer);
      let selectTtem = document.getElementById(this.answer);
      selectTtem.style.backgroundColor = "red";
      correctItem.style.backgroundColor = "green";
      console.log(correctItem);
    },
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
